//
//  XQAlbumListViewController.swift
//  PhotoSelect
//
//  Created by 王帅强 on 2019/1/7.
//  Copyright © 2019 王帅强. All rights reserved.
//

import UIKit

class XQAlbumListViewController: UIViewController {

    lazy var albumVM = XQAlbumViewModel()
    let identifier = "XQAlbumCell"

    var collectionView: UICollectionView?

    override func viewDidLoad() {
        super.viewDidLoad()

        initUI()
        loadAlumbList()
    }

}

extension XQAlbumListViewController {
    func initUI() {

        let layout = UICollectionViewFlowLayout()
        collectionView = UICollectionView(frame: view.frame, collectionViewLayout: layout)
        collectionView?.backgroundColor = UIColor.red
        collectionView?.delegate = self
        collectionView?.dataSource = self

        collectionView?.register(UINib(nibName: "XQAlbumCell", bundle: nil), forCellWithReuseIdentifier: identifier)


        view.addSubview(collectionView!)
    }

    func loadAlumbList()  {
        albumVM.loadAlbumList { (success, tipMsg) in
            if (success) {
                print(self.albumVM.albumList.count)
                DispatchQueue.main.async(execute: {
                    self.collectionView?.reloadData()
                })
            }
        }
    }
}

extension XQAlbumListViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: 200, height: 250)
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return albumVM.albumList.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) as! XQAlbumCell
        cell.configData(album: albumVM.albumList[indexPath.item])

        return cell
    }


    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let vc = XQPhotoListViewController()
        vc.albumAssetsResult = albumVM.albumList[indexPath.item].assetsResult
        self.present(vc, animated: true, completion: nil)
    }
}
